package logic

import (
	"context"
	"io"
	"net/http"
	"os"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DownloadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDownloadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DownloadLogic {
	return &DownloadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DownloadLogic) Download(req types.DownloadRequest,r *http.Request,w http.ResponseWriter) error {
	// todo: add your logic here and delete this line
	if req.Dir == "" || req.Filename == "" {
		return errorx.NewBizError(500,"路径不正确")
	}
	file,err := os.Open(common.BaseFileURI + req.Dir + "/" + req.Filename)
	if err != nil {
		return errorx.NewBizError(500,err.Error())
	}
	defer file.Close()
	//设置响应的header头
	// 以filename为文件名下载
	// w.Header().Add("Content-type", "application/octet-stream")
	// w.Header().Add("content-disposition", "attachment; filename=\""+req.Filename+"\"")
	w.Header().Add("content-disposition", "inline")
	//将文件写至responseBody
	_, err = io.Copy(w, file)
	return err
}
